<?php

namespace App\HttpController\V1;

use Swoole\Exception;
use App\Tools\Token\Token;
use EasySwoole\EasySwoole\Config;

class Auth extends BaseWithDb
{
    protected $user;

    function onRequest( ?string $action ): ?bool
    {

        try {
            $parentReturn = parent::onRequest( $action );
            $jwt = $this->request()->getHeader( Config::getInstance()->getConf( 'TOKEN_NAME' ) )[0]??'';
            if ( empty( $jwt ) ) {
                throw new Exception( '请先登录' );
            }
            $data = Token::decode( $jwt );
            if ( $data['status'] == false ) {
                throw new Exception( $data['content'] );
            }
            $this->user = $data['content'];
            if ( empty( $this->user->token ) ) {
                throw new Exception( '登录信息已失效,请重新登录' );
            }
            $jwtToken = $this->redis->get( 'jwtToken' . $this->user->id );
            if ( $jwtToken !== $this->user->token ) {
                throw new Exception( '您的账号已在其它地方登陆，若不是本人操作，请注意账号安全！' );
            }

            $request_uri = $this->request()->getServerParams()['request_uri'];
//            $controller = explode( "/", $request_uri );
//            $controller = array_map( "strtolower", $controller );
//            foreach ( $this->controllerAll as $item ) {
//                if ( in_array( strtolower( $item ), $controller ) ) {
//                    return $parentReturn;
//                }
//            }

            return $parentReturn;
        } catch ( Exception $e ) {
            return $this->writeJson( 2000, null, $e->getMessage() );
        }
    }

}